package com.xxxt.filter;

import com.alibaba.fastjson.JSONObject;
import com.xxxt.utils.TokenUtil;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

/**
 * 自定义token拦截器
 *
 * @author mopeiwen
 * @date 2020/03/01 21:40:59
 */
public class TokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		int status = 0;
		String message = "";
		JSONObject json = new JSONObject();
		
		// token验证错误
		String token = request.getHeader("Authorization");
		if (token != null ) {
			// 验证token是否正确
			boolean result = TokenUtil.verify(token);
			if (result) {
				return true;
			}else {
				status = 44;// token验证错误
				message = "身份信息验证错误或已过期";
			}
		} else {
			status = 44;// token验证错误
			message = "身份信息验证错误或已过期";
		}
		json.put("status", status);
		json.put("message", message);
		responseMessage(response, response.getWriter(), json);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	/**
	 * 返回信息给客户端
	 *
	 * @param response
	 * @param out
	 * @param apiResponse
	 */
	private void responseMessage(HttpServletResponse response, PrintWriter out, JSONObject jsonObject) {
		response.setContentType("application/json; charset=utf-8");
		out.print(jsonObject);
		out.flush();
		out.close();
	}
}
